package org.csc.sss.datacore.security;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.csc.sss.util.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class MySimpleUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败========================>");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String msg = null;
        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
            msg = "用户名或密码输入错误，登录失败!";
        } else if (exception instanceof DisabledException) {
            msg = "账户被禁用，登录失败，请联系管理员!";
        } else {
            msg = "登录失败!";
        }
        super.setDefaultFailureUrl("/public/failure?msg=" + msg);
        super.setUseForward(true);
        super.onAuthenticationFailure(request, response, exception);
    }

}
